//
//  LTY_SearchViewController.m
//  MooMusic
//
//  Created by 守护神 on 15/10/26.
//  Copyright © 2015年 wjy. All rights reserved.
//

#import "LTY_SearchViewController.h"
// 导入tableview的头文件
#import "LTY_SearchTableViewCell.h"
// 导入NetWork头文件
#import "NetWork.h"
// 导入searchModel的头文件
#import "LTY_SearchModel.h"
// 导入单曲头文件
#import "LTY_SingleSongViewController.h"
// 导入fmdb的头文件
#import "FMDB.h"

@interface LTY_SearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>

// 定义一个搜索框
@property (nonatomic, strong)UISearchBar *searchBar;
@property (nonatomic, strong)UITableView *searchTableView;
// 设置一个数据源
@property (nonatomic, strong)NSMutableArray *DataArray;
// 清空历史的button
@property (nonatomic, strong)UIButton *clearButton;
// 定义一个数据库的属性
@property(nonatomic, strong)FMDatabase *db;
// 创建一个history的数组
@property (nonatomic, strong)NSMutableArray *history;
// 创建一个用来存放倒序的数组
@property (nonatomic, strong)NSMutableArray *reversedArray;

@end

static NSString *const cellInderfier = @"cellInderfier";
static NSString *const cellIn = @"cellIn";


@implementation LTY_SearchViewController

- (void)dealloc
{
    // 只要注册一个观察者, 一定要在类的dealloc方法中, 移除掉自己的观察者身份
    // 在ARC下也一样
    NSNotificationCenter *pushCenter = [NSNotificationCenter defaultCenter];
    [pushCenter removeObserver:self];
}


// 初始化消息通知
- (instancetype)init
{
    self = [super init];
    if (self) {
       
        NSNotificationCenter *pushCenter = [NSNotificationCenter defaultCenter];
        [pushCenter addObserver:self selector:@selector(pushNotifica:)
                       name:@"PushNextViewController" object:nil];
        
    }
    
    return self;
}

- (void)pushNotifica:(NSNotification *)center
{
    LTY_SingleSongViewController *singleVC = [[LTY_SingleSongViewController alloc] init];
    // searchBar从父视图上移除
    [self.searchBar removeFromSuperview];
    // 消息传值
    NSString *string = [center object];
    singleVC.SearchStr = string;
    //往fmdb数据库里插入数据 (搜索框的内容)
    [self.db executeUpdate:@"INSERT INTO t_History (name) VALUES (?);", string];
    [self.navigationController pushViewController:singleVC animated:YES];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.DataArray = [NSMutableArray array];
        self.history = [NSMutableArray array];
        self.reversedArray = [NSMutableArray array];
    }
    return self;
}
#pragma mark -- 返回按钮触发的方法
- (void)backItemAction
{
    [self.navigationController popViewControllerAnimated:YES];
    // searchBar从父视图上移除
    [self.searchBar removeFromSuperview];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self creatSearchBar];
    
    if ([self.db open]) {
    // 1.执行查询语句
    FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM t_History"];
    // 2.遍历结果
    while ([resultSet next]) {
        NSString *name = [resultSet stringForColumn:@"name"];
        if (self.history.count > 0) {
            for (int i = 0; i < self.history.count; i++) {
                if ([self.history containsObject:name]) {
                    NSLog(@"不进行重复添加!");
                }else{
                    [self.history addObject:name];
                    NSLog(@"name = %@",name);
                }
            }
            
            
        }else{
            [self.history addObject:name];
        }
        // 刷新tableview
        [self.searchTableView reloadData];
        
    }


        
        
   }

    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    
    // 添加导航栏退回按钮
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backItemAction)];
    self.navigationItem.leftBarButtonItem = backItem;
    
    
    //1.获得数据库文件的路径
    NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"fmdb______  %@", doc);
    
    NSString *fileName=[doc stringByAppendingPathComponent:@"History.sqlite"];
    //2.获得数据库
    FMDatabase *db=[FMDatabase databaseWithPath:fileName];
    
    [db open];
    
    //3.打开数据库
    if ([db open]) {
        //4.创表
        BOOL result=[db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_History (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL);"];
        if (result) {
            
            NSLog(@"创表成功");
            
        }else{
            
            NSLog(@"创表失败");
            
        }
        
        
    }
    
    self.db = db;

    
    
    // 创建searchbar
    //[self creatSearchBar];
    // 创建Tableview
    [self creatSearchTableView];
    // 获取数据
    [self searchData];
    
    // Do any additional setup after loading the view.
}
// 获取数据
- (void)searchData
{
    // 请求数据
    [NetWork networkGETRequestWithURL:searchString Paramater:nil ResultBlock:^(id result) {
        //NSLog(@"++++++  %@", result);
        NSMutableArray *dataArr = [NSMutableArray array];
        dataArr = [result objectForKey:@"data"];
        
        // 解析后把model存放刀数据源里
        self.DataArray = [LTY_SearchModel arrayWithModelByArray:dataArr];
        
        
        if (self.DataArray.count > 0) {
            // 刷新tableview
            [self.searchTableView reloadData];
        }
        
        // 创建的时候使tableview的线显示
        self.searchTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        
    }];
}

// 创建searchbar
- (void)creatSearchBar
{
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(70, -10, SCREENWIDTH - 90 , 60)];
    [[UISearchBar appearance] setBarTintColor:[UIColor blackColor]];
    _searchBar.barTintColor = [UIColor redColor];
    _searchBar.placeholder = @"搜索单曲";
    [_searchBar setBarStyle:UIBarStyleBlackOpaque];
    [_searchBar setSearchBarStyle:UISearchBarStyleMinimal];
    [_searchBar setShowsCancelButton:NO];
    _searchBar.returnKeyType = UIReturnKeySearch;
    _searchBar.delegate = self;
    [self.navigationController.navigationBar addSubview:_searchBar];
}

// 创建Tableview
- (void)creatSearchTableView
{
    self.searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT - 128) style:UITableViewStylePlain];
    self.searchTableView.delegate = self;
    self.searchTableView.dataSource = self;
    self.searchTableView.backgroundColor = [UIColor whiteColor];
    [self.searchTableView registerClass:[LTY_SearchTableViewCell class] forCellReuseIdentifier:cellInderfier];
    [self.searchTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIn];
    // 创建的时候使tableview的线隐藏
    self.searchTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, 50)];
    footerView.backgroundColor = [UIColor whiteColor];

    self.clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.clearButton.frame = CGRectMake(SCREENWIDTH / 2 - 60, 5, 120, 40);
    self.clearButton.backgroundColor = [UIColor redColor];
    [self.clearButton setTitle:@"清除历史搜索" forState:UIControlStateNormal];
    self.clearButton.layer.cornerRadius = 15;
    self.clearButton.clipsToBounds = YES;
    [self.clearButton addTarget:self action:@selector(clearButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:self.clearButton];
    
    self.searchTableView.tableFooterView = footerView;
    
    [self.view addSubview:self.searchTableView];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.DataArray.count > 0) {
    if (section == 0) {
        return 1;
    }else{
        if (self.history.count > 0) {
            return self.history.count;
        }else{
            return 0;
        }
    }
    
    }else{
        return 0;
    }
        
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
       LTY_SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellInderfier];
        // 把array数组给传递过去
        if (self.DataArray.count > 0) {
            cell.tempDataArray = self.DataArray;
        }
        
        return cell;
        
    }else{
        
        UITableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:cellIn];
        
        if (self.history.count > 0) {
            // 强转可能会出现crash 注意:
            self.reversedArray = (NSMutableArray *)[[self.history reverseObjectEnumerator] allObjects];
            cell2.textLabel.text = [self.reversedArray objectAtIndex:indexPath.row];
        }
        
        return cell2;
    }

    
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSLog(@"点击cell触发的方法");
    if (indexPath.section == 1) {
        LTY_SingleSongViewController *singleVC = [[LTY_SingleSongViewController alloc] init];
        // 强转可能会出现crash 注意:
        self.reversedArray = (NSMutableArray *)[[self.history reverseObjectEnumerator] allObjects];
        singleVC.SearchStr = self.reversedArray[indexPath.row];
        // searchBar从父视图上移除
        [self.searchBar removeFromSuperview];
        [self.navigationController pushViewController:singleVC animated:YES];
        
    }
}

// 分区的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.DataArray.count > 0) {
    if (section == 0) {
        return @"搜索热词";
    }else{
        return @"搜索历史";
    }
    
    }else{
        return @"";
    }
}

// tableview的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 120;
    }else{
        return 50;
    }
}

#pragma mark -- SearchBarDelegate
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"search按钮触发的方法");
    
    //往fmdb数据库里插入数据 (搜索框的内容)
    [self.db executeUpdate:@"INSERT INTO t_History (name) VALUES (?);", _searchBar.text];

    // searchBar从父视图上移除
    [self.searchBar removeFromSuperview];
    
    LTY_SingleSongViewController *singleVC = [[LTY_SingleSongViewController alloc] init];
    // 把输入框的输入字给传递过去
    singleVC.SearchStr = searchBar.text;
    [self.navigationController pushViewController:singleVC animated:YES];
}

#pragma mark -- 清除历史搜索按钮触发的方法
- (void)clearButtonAction
{
    NSLog(@"清除历史搜索");
    [self.history removeAllObjects];
    [self delete];
    [self.searchTableView reloadData];
}

//删除数据
-(void)delete
{
    //    [self.db executeUpdate:@"DELETE FROM t_student;"];
    [self.db executeUpdate:@"DROP TABLE IF EXISTS t_History;"];
    [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_History (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL);"];
}




- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = 40;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
